import { Input, Tree } from "antd";
import { useState, useEffect, useMemo, forwardRef, useImperativeHandle } from "react";
import {
  listTree,
  searchAppMenu,
} from '@/api/appMenuResources/appMenuResources'
import { useQuery } from "@tanstack/react-query";
import { expandTree } from "@/utils";
import { useThemeToken } from "@/theme/hooks";
const SelectMenuTree = forwardRef((props, ref) => {
  const { wantRoot, id, rootName, onTreeChange } = props
  const { colorLink } = useThemeToken();
  const [queryParam, setQueryParam] = useState({
    resourceName: ''
  });
  const [expandedKeys, setExpandedKeys] = useState([]);

  useImperativeHandle(ref, () => ({
    refetch: refetch,
  }));

  const { data: treeData, isFetching, refetch } = useQuery({
    queryKey: ['selectMenuTree-listTree', queryParam, id],
    initialData: props.treeData,
    queryFn: () => {
      if (queryParam.resourceName) {
        return searchAppMenu(queryParam).then((res) => {
          return res.data || []
        })
      } else {
        return listTree(id || '0', 20).then((res) => {
          return res.data || []
        })
      }
    },
    staleTime: 0,
  })

  const treeOptions = useMemo(() => {
    if (wantRoot && !queryParam.resourceName) {
      return [
        {
          id: '-1',
          title: rootName || '根节点',
          children: treeData || [],
          attributes: {
            deptType: 'dept'
          }
        }
      ]
    }
    return treeData
  }, [treeData, wantRoot])

  useEffect(() => {
    if (treeOptions) {
      setExpandedKeys(expandTree(treeOptions, 3))
      onTreeChange && onTreeChange([...treeOptions])
    }
  }, [treeOptions])

  const onSearch = (value) => {
    setQueryParam({ resourceName: value })
  }

  return (
    <div>
      {props.showSearch && <Input.Search style={{ paddingBottom: '16px' }} placeholder="输入名称回车查询" onSearch={onSearch} />}
      <Tree
        selectedKeys={props.selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={props.onSelect}
        autoExpandParent={true}
        fieldNames={{ title: 'title', key: 'id' }}
        treeData={treeOptions}
        titleRender={(node) => {
          return <span style={{ whiteSpace: 'nowrap' }}>{node.title}</span>
        }}
        onExpand={(expandedKeys) => {
          setExpandedKeys(expandedKeys)
        }}
      ></Tree>
    </div>
  );
});

export default SelectMenuTree;